import { message } from 'antd';
import axios from 'axios';
import { useUserStore } from '@/stores';
import { tryApiRequest } from '@hdtd/utils';

tryApiRequest.setCtx({
  messageApi: {
    error: message.error,
    success: message.success
  }
});

const httpClient = axios.create({
  timeout: 200000,
  adapter: 'fetch'
});

httpClient.interceptors.request.use(
  async (config) => {
    const { accessToken, logout } = useUserStore.getState();
    if (accessToken) {
      config.headers['X-Access-Token'] = accessToken;
    } else {
      if (!window.location.hash.includes('/login')) {
        message.error('请先登录');
        logout();
        return Promise.reject('未登录');
      }
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
httpClient.interceptors.response.use(
  (response) => response,
  (error) => Promise.reject(error)
);

export default httpClient;
